package cmd

import (
	"context"
	"encoding/json"
	"log"
	"strconv"

	"github.com/hibiken/asynq"
	"github.com/spf13/cobra"
	"pets.ser163.cn/config"
)

var queueCmd = &cobra.Command{
	Use:   "asynq",
	Short: "Run asynq server",
	Run: func(cmd *cobra.Command, args []string) {
		log.Println("Running asynq queue...")
		startAsynqServer()
	},
}

func init() {
	rootCmd.AddCommand(queueCmd)
}

type PayloadStruct struct {
	UserId int `json:"user_id"`
}

func startAsynqServer() {
	if config.ConfigInstance.Redis.Use && config.ConfigInstance.Asynq.Use {
		addr := config.ConfigInstance.Redis.Host + ":" + strconv.Itoa(config.ConfigInstance.Redis.Port)
		r := asynq.RedisClientOpt{Addr: addr}
		srv := asynq.NewServer(r, asynq.Config{Concurrency: 10})

		mux := asynq.NewServeMux()
		var payload PayloadStruct
		mux.HandleFunc("send_email", func(c context.Context, t *asynq.Task) error {
			payloadBytes := t.Payload()
			if err := json.Unmarshal(payloadBytes, &payload); err != nil {
				// 处理错误
				log.Println(err.Error())
			}

			log.Printf("Sending email to user: %d", payload.UserId)
			return nil
		})

		if err := srv.Run(mux); err != nil {
			log.Fatalf("could not run server: %v", err)
		}
	}
}
